<template>
    <div class="channelCondition">
        <!-- <nutbTitle title="通道组设置"></nutbTitle> -->
        <nu-row class="row" :gutter="20">
            <nu-col :span="24" class="col">
                <span class="hint">一级调度为一个通道组，两级调度为两个通道组，三级调度为三个通道组。</span>
            </nu-col>
            <nu-col :span="24" class="col">
                <nu-button type="primary" class="searchButton" @click="plantNameSetting">电厂名称设置</nu-button>
                <nu-button type="primary" class="searchButton" @click="addTable">新增通道组</nu-button>
            </nu-col>
            <nu-col :span="24">
                <div class="line"></div>
            </nu-col>
        </nu-row>

        <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
            :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
            @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange">
        </NuTableList>
        <!-- 新增 -->
        <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="42%" center :close-on-click-modal="false"
            top="15vh" :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="110px" class="submitForm"
                    @submitForm="diaSubmitForm" :buttons="fyButtons">
                    <NuformItem label="通道组名称" prop="groupName" width="100%"
                        :rules="[{ required: true, message: '通道名称不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.groupName" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="遥测起始地址" prop="addressYc" width="100%"
                        :rules="[{ required: true, message: '遥测起始地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.addressYc" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="遥信起始地址" prop="addressYx" width="100%"
                        :rules="[{ required: true, message: '遥信起始地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.addressYx" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="遥调起始地址" prop="addressYt" width="100%"
                        :rules="[{ required: true, message: '遥调起始地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.addressYt" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                    <NuformItem label="遥控起始地址" prop="addressYk" width="100%"
                        :rules="[{ required: true, message: '遥控起始地址不能为空' }]">
                        <nu-input type="text" v-model="dialogFormData.addressYk" size="middle"
                            :disabled="dialogFormDisabled" placeholder="请输入"></nu-input>
                    </NuformItem>
                </NuVerifyForm>
                <div style="text-align: right;">
                    <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                    <nu-button class="dialogSearchButton" type="primary" @click="diaSave">确定</nu-button>
                </div>
            </div>
        </nu-dialog>
        <!-- 电厂名称设置 -->
        <nu-dialog title="电厂名称设置" :visible.sync="dialogNameShow" width="42%" center :close-on-click-modal="false" top="15vh"
            :modal-append-to-body="false" @close="diaClose">
            <div class="dialogHeaderSearch">
                <NuVerifyForm :model="formData" ref="formData" label-width="110px" class="submitForm"
                    @submitForm="diagNameSubmitForm" :buttons="fyButtons">
                    <NuformItem label="电厂名称" prop="channelName" width="100%"
                        :rules="[{ required: true, message: '电厂名称不能为空' }]">
                        <nu-input type="text" v-model="formData.channelName" size="middle" :disabled="dialogFormDisabled"
                            placeholder="请输入"></nu-input>
                    </NuformItem>
                </NuVerifyForm>
                <div style="text-align: right;">
                    <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
                    <nu-button class="dialogSearchButton" type="primary" @click="diaNameSave">确定</nu-button>
                </div>
            </div>
        </nu-dialog>
        <!-- 上传 -->
        <nu-dialog :title="upload.title" :visible.sync="upload.open" width="30%" center :close-on-click-modal="false"
            top="5vh" :modal-append-to-body="false">
            <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url"
                :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                :auto-upload="false" drag :data="upload.data" name="file">
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <!-- <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                                                                                                                                                        @click="importTemplate">下载模板</el-link> -->
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </nu-dialog>
    </div>
</template>
    
<script>
import nuCol from "@/components/base/col.vue"
import nuRow from "@/components/base/row.vue";
import nutbTitle from "@/components/base/tableTitle.vue"
import NuVerifyForm from "@/components/verify-form"
import NuformItem from "@/components/verify-form/form-item.vue"
import nuInput from "@/components/base/input"
import nuSelect from "@/components/base/select"
import nuButton from "@/components/base/button"
import NuTableList from "@/components/tableList/TableFormList"
import nuDialog from "@/components/base/dialog"
import nuRadio from "@/components/base/radio"
import nuRadioButton from "@/components/base/radio-button"
import axios from 'axios'
import { getToken } from "@/utils/auth";
const operates = that => [
    {
        label: '编辑',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.openEdit(row);
        },
    },
    {
        isShow: row => {
            return false;
        },
    },
    {
        label: '删除',
        icon: '',
        width: '50px',
        isShow: row => {
            return true;
        },
        disabled: row => {
            return false;
        },
        method: row => {
            that.tbRowdetele(row);
        },
    },
];
export default {
    name: "channelGroupSet",
    components: { nuCol, nuRow, nutbTitle, NuVerifyForm, NuformItem, nuInput, nuSelect, nuButton, NuTableList, nuDialog, nuRadio, nuRadioButton },
    data() {
        return {
            formData: {
                channelName: "",
                plantId: "",
                plantType: "",
                powerEnable: ""
            },
            dialogFormData: {
                identification: true,
                groupName: "",// 新增通道定义input
                addressYc: "",
                addressYx: "",
                addressYt: "",
                addressYk: ""
            },
            operates,
            fyButtons: [],
            currentRow: null,
            pagination: {
                pageSize: 20,
                total: 0,
                pageNum: 1,
            },
            dialogTitle: '',
            dialogShow: false,
            dialogNameShow: false,
            columns: [
                {
                    label: '序号',
                    prop: 'ranking',
                    width: '70px',
                    render: (h, params) => {
                        return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
                    },
                },
                {
                    label: '通道组名称',
                    prop: 'groupName',
                    width: 150
                },
                {
                    label: '遥测起始地址',
                    prop: 'addressYc',
                    width: 150
                },
                {
                    label: '遥信起始地址',
                    prop: 'addressYx',
                    width: 150
                },
                {
                    label: '遥调起始地址',
                    prop: 'addressYt',
                    width: 150
                },
                {
                    label: '遥控起始地址',
                    prop: 'addressYk',
                    width: 150
                },
                {
                    label: '关联通道',
                    prop: 'channels',
                    render: (h, params) => {
                        let strChannels = ""

                        return h('span', params.row.channels.join("，"));
                    },
                }
            ],
            dataSource: [{}],
            options: {
                'default-expand-all': true,
                'element-loading-background': 'rgba(225,239,242)',
                'element-loading-text': '数据正在加载中',
                'row-key': 'pid',
                'header-cell-style': {
                    background: 'rgba(105, 159, 209, 0.7)',
                    color: '#fff',
                    fontWeight: 'bold',
                    fontsize: '16px',
                },
                height: 'calc(100vh - 350px)',
                props: {
                    fixed: 'right'
                }
            },
            // 用户导入参数
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + window.api.importChannelCondition,
                // 上传时附带的额外参数
                data: { id: 1 }
            },
        };
    },
    computed: {
        dialogFormDisabled() {
            return this.dialogTitle == '详情'
        }
    },
    created() {
    },
    mounted() {
        this.getChannelGroupSet();
        this.getParticipants()
    },
    methods: {
        /**
         * 查询
         */
        searchTable() {
            this.$refs['formData'].searchForm('form');
        },
        /**
         * form组件内置查询事件
         */
        searchForm(val) {
            if (val) {
                this.getChannelGroupSet();
            }
        },
        /**
         * 每页条数变化事件
         */
        handleSizeChange(val) {
            this.pagination.currentPage = 1;
            this.pagination.pageSize = val;
            this.getChannelGroupSet();
        },
        /**
         * 改变分页触发事件
         */
        handleChangePage(val) {
            this.pagination.currentPage = val;
            this.getChannelGroupSet();
        },
        /**
         * 单选
         */
        handleCurrentChange(val) {
            this.currentRow = val
        },
        /**
         * 电厂修改名称
         */
        saveParticipant() {
            let postData = {
                id: this.formData.plantId,
                name: this.formData.channelName,
                // plantType:this.formData.plantType,
                // powerEnable:this.formData.powerEnable
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.saveParticipant, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                    this.diaClose()

                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 清除数据
         */
        clearParams() {
            this.resetForm('formData')
        },
        /**
         * 重置表单
         */
        resetForm(formName) {
            if (this.$refs[formName]) {
                this.$refs[formName].resetForm('form');
            }
            for (let k in this[formName]) {
                if (Object.prototype.toString.call(this[formName][k]) == "[object String]") {
                    this[formName][k] = ''
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Array]") {
                    this[formName][k] = []
                } else if (Object.prototype.toString.call(this[formName][k]) == "[object Number]") {
                    this[formName][k] = ''
                }
            }
        },
        /**
         * 新增
         */
        addTable() {
            this.dialogTitle = '新增通道组'
            this.dialogShow = true
            this.dialogFormData.identification = true
        },
        plantNameSetting() {
            this.dialogNameShow = true
            this.getParticipants()

        },
        getParticipants() {
            let postData = {
                ...this.pagination,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpGet(window.api.getParticipants, postData).then(res => {
                if (res.code == 200) {
                    this.formData.channelName = res.rows[0].name
                    this.formData.plantId = res.rows[0].id
                    this.formData.powerEnable = res.rows[0].powerEnable
                    this.formData.plantType = res.rows[0].plantType
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 表格-删除
         */
        tbRowdetele(row) {
            if (!row.associatedChannel) {
                this.$confirm('确定要删除【' + row.groupName + '】吗？', '确认删除', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.delChannelGroupSet(row)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            } else {
                this.$message('该通道组下关联其他通道，先解除关联关系，方可删除');
            }

        },
        /**
         * 删除表格数据
         */
        delChannelGroupSet(row) {
            // console.log(row)
            let postData = {
                id: row.id
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.$httpGet(window.api.delChannelGroupSet, postData).then(res => {
                if (res.code == 200) {
                    this.getChannelGroupSet();
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 设置为主通道
         */
        openMainChannel(row) {
            this.$confirm('是否将此通道设置为主通道，后续系统计算以主通道数据为准。', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.setMainChannel(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        /**
         * dialogFormData组件内置提交事件
         */
        diaSubmitForm(val) {
            if (val) {
                if (this.dialogTitle == '编辑通道组') {
                    this.addChannelCondition()
                } else if (this.dialogTitle == '新增通道组') {
                    this.addChannelCondition()
                }
            }
        },
        /**
         * 弹窗-单点新增-保存
         */
        diaSave() {
            this.$refs['dialogFormData'].submitForm('form');

        },
        /**
         * 弹窗-单点新增-关闭
         */
        diaClose() {
            this.resetForm('dialogFormData')
            this.dialogShow = false
            this.dialogNameShow = false
        },
        /**
         * 电厂名称
         */
        diagNameSubmitForm(val) {
            if (val) {
                this.saveParticipant()
            }
        },
        /**
         * 弹窗-电厂名称-保存
         */
        diaNameSave() {
            this.$refs['formData'].submitForm('form');
        },
        /**
         * 获取表格数据
         */
        getChannelGroupSet() {
            let postData = {
                ...this.formData,
                ...this.pagination,
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.$httpGet(window.api.getChannelGroupSet, postData).then(res => {
                // console.log(res)
                if (res.code == 200 && res.rows) {
                    this.pagination.total = res.total;
                    this.dataSource = res.rows;

                } else {
                }
            }).catch(err => {

            });
        },
        /**
         * 新增接口
         */
        addChannelCondition() {
            let postData = {
                ...this.dialogFormData,
                plantId: this.formData.plantId,
                plantName: this.formData.channelName
            };

            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.$httpPost(window.api.saveChannelGroup, postData).then(res => {
                if (res.code == 200) {
                    this.$message({
                        message: '成功',
                        type: 'success'
                    })
                    this.diaClose()
                    this.getChannelGroupSet();
                } else {
                }
            }).catch(err => { });
        },
        /**
         * 设置为主通道
         */
        setMainChannel(row) {
            let postData = {
                id: row.id
            };
            for (let k in postData.query) {
                if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
                    postData.query[k] = postData.query[k].toString().trim();
                }
            }
            this.dataSource = [];
            this.$httpPost(window.api.setMainChannel, postData).then(res => {
                if (res.success) {
                    this.$message({
                        type: 'success',
                        message: '成功!'
                    });
                    this.getChannelGroupSet()
                } else {
                }
            }).catch(err => {

            });
        },
        // 文件上传中处理
        handleFileUploadProgress(event, file, fileList) {
            this.upload.isUploading = true;
        },
        // 文件上传成功处理
        handleFileSuccess(response, file, fileList) {
            this.upload.open = false;
            this.upload.isUploading = false;
            this.$refs.upload.clearFiles();
            this.$message({
                message: response.message,
                type: 'success'
            })
            this.searchTable();
        },
        // 提交上传文件
        submitFileForm() {
            this.$refs.upload.submit();
        },
        /**
         * 表格-编辑
         */
        openEdit(row) {
            this.dialogTitle = '编辑通道组'
            Object.assign(this.dialogFormData, row)
            this.dialogShow = true
        },
    }
};
</script>
    
<style scoped lang="scss">
.channelCondition {
    height: calc(100vh - 70px);
}

.hint {
    display: block;
    font-size: 14px;
    line-height: 28px;
    color: rgba(79, 84, 112, 1);
}

.searchForm {
    // height: calc(100% - 40px);
    display: flex;
    align-items: center;
    position: relative;
}

.submitForm {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    padding-right: 160px;
}

.btnBox {
    display: flex;
    float: right;
    z-index: 10;
    position: absolute;
    top: 15px;
    right: 10px;
}

.dialogHeaderSearch {
    background-color: var(--model-bgc);
    padding: 10px;
    margin-top: 10px;
    display: flex;
    flex-wrap: wrap;
    justify-content: right;
    flex-direction: column;

    .el-form-item {
        margin-bottom: 4px;

        ::v-deep .el-form-item__error {
            padding-top: 0;
        }
    }
}

::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
        width: auto;
    }
}

::v-deep .el-dropdown {
    position: absolute;
    right: 10px;
    top: 2px;
}

::v-deep .el-button--primary {
    background-color: rgba(71, 99, 255, 1);
    border-color: rgba(71, 99, 255, 1);
}
</style>
    
    